import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:znmm/UI/A_Common/image/cached_network_Image.dart';
import 'package:znmm/UI/A_Common/star_rating_bar.dart';
import 'package:znmm/UI/CategoryPages/mag/category_mag.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/config/app_asset.dart';
import 'package:znmm/config/app_color.dart';
import 'package:znmm/config/app_style.dart';

import '../mag/product_mag.dart';
import '../model/product_model.dart';
import '../show_product_view.dart';

class ProductAllView extends StatefulWidget {
  const ProductAllView({super.key});

  @override
  State<ProductAllView> createState() => _ProductAllViewState();
}

class _ProductAllViewState extends State<ProductAllView> {
  late List<ProductModel> _pModelList = [];

  @override
  void initState() {
    super.initState();
    _pModelList = ProductMag().getAllProducList();
    _requestData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _requestData() {
    ProductMag().reqAllProudut(
      callback: () {
        if (mounted) {
          setState(() {
            _pModelList = ProductMag().getAllProducList();
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppColor.backgroundColor,
        appBar: MyGlobal.getNavigationBar(context, "Home / Product", actions: [
          // IconButton(
          //   onPressed: () {
          //     _requestData();
          //   },
          //   icon: const Icon(Icons.refresh),
          //   tooltip: 'refresh',
          //   color: Colors.black,
          // )
        ]),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: const EdgeInsets.fromLTRB(16, 5, 10, 5),
              child: Text(
                "Products: ${_pModelList.length}",
                overflow: TextOverflow.ellipsis,
                style:
                    const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
            Expanded(
                child: Container(
              color: Colors.white,
              padding: const EdgeInsets.all(5),
              child: _pModelList.isNotEmpty
                  ? MediaQuery.removePadding(
                      removeTop: true,
                      context: context,
                      child: GridView.builder(
                        padding: const EdgeInsets.all(10.0),
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2, // 设置为两列
                          crossAxisSpacing: 10.0, // 列之间的间距
                          mainAxisSpacing: 10.0, // 行之间的间距
                          childAspectRatio: 0.75, // 设置子项的宽高比
                        ),
                        itemCount: _pModelList.length + 1,
                        itemBuilder: (_, index) {
                          if (index < _pModelList.length) {
                            ProductModel furniture = _pModelList[index];
                            return Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(8.0),
                                border: Border.all(
                                  color: Colors.grey,
                                  width: 0.5,
                                ),
                              ),
                              child: Padding(
                                padding:
                                    const EdgeInsets.fromLTRB(10, 0, 10, 0),
                                child: _listViewItem(furniture, index),
                              ),
                            );
                          } else {
                            return GestureDetector(
                              onTap: () {
                                print("Show More");
                                ProductMag().reqAllProudut(
                                  showMore: true,
                                  callback: () {
                                    if (mounted) {
                                      setState(() {
                                        _pModelList =
                                            ProductMag().getAllProducList();
                                      });
                                    }
                                  },
                                );
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(8.0),
                                  border: Border.all(
                                    color: Colors.grey,
                                    width: 0.5,
                                  ),
                                ),
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Image.asset(
                                      AppAsset.imageLogo,
                                    ),
                                    Container(
                                      height: 36,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: Colors.black,
                                        borderRadius:
                                            BorderRadius.circular(2.0),
                                      ),
                                      child: const Text(
                                        "Show More",
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }
                        },
                      ),
                    )
                  : MyGlobal.emptyWidget(),
            )),
            const SizedBox(
              height: 10,
            )
          ],
        ));
  }

  Widget _listViewItem(ProductModel pducMol, int index) {
    return GestureDetector(
      onTap: () {
        String sulgStr = pducMol.slug;
        print("sulgStr:$sulgStr");
        CategoryMag().reqProductBySlugGraql(
          sulgStr,
          callback: (p0) {
            ProductModel pmodel = p0;
            Get.to(ShowProductView(
              product: pmodel,
            ));
          },
        );
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Center(
              child: ClipRRect(
                borderRadius: BorderRadius.circular(15.0),
                child: pducMol.sourceUrl.isNotEmpty
                    ? CachedNetworkImageLoader(
                        imageUrl: pducMol.sourceUrl,
                      )
                    : Image.asset(pducMol.imagesList[0],
                        width: 150, height: 150),
              ),
            ),
          ),
          const SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.fromLTRB(3, 0, 3, 0),
            child: Text(
              pducMol.name,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              StarRatingBar(score: pducMol.averageRating),
              const SizedBox(width: 10),
              Text(pducMol.averageRating.toString(), style: h4Style),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Icon(
                pducMol.stockStatus == "OUT_OF_STOCK"
                    ? Icons.close
                    : Icons.done,
                size: 24,
                color: pducMol.stockStatus == "OUT_OF_STOCK"
                    ? Colors.red
                    : AppColor.blue,
              ),
              const SizedBox(width: 10),
              Expanded(child: Text(pducMol.stockStatus, style: h4Style)),
            ],
          ),
          Text(pducMol.price,
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize: 16,
                  color: AppColor.blue,
                  fontWeight: FontWeight.bold)),
          const SizedBox(
            height: 5,
          ),
          Container(
            height: 36,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.circular(2.0),
            ),
            child: const Text(
              "View",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold),
            ),
          ),
          const SizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }
}
